﻿
using System;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Web.Security;
namespace Business
{
    
    public class FileTools
    {
        private static void CreateFolder(string mapPathAddress)
        {
            try
            {
                if (!System.IO.Directory.Exists(mapPathAddress))
                {
                    System.IO.Directory.CreateDirectory(mapPathAddress);
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        public static Boolean SaveFiles(FileCollectionEventArgs e, HttpContext httpCurrent,string folder, Guid taskId,Guid DocId,DateTime Date)
        {
            bool result = true;
            try
            {

                List<FileProperty> savedFileNames = SaveFiles(e, httpCurrent, folder);
                foreach (FileProperty f in savedFileNames)
                {
                    DataAccess.TblFile.Insert(Guid.NewGuid(), taskId, f.NewFileName, Date, f.OriginalFileName, (Guid)Membership.GetUser().ProviderUserKey, DocId);
                }
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }

        private static List<FileProperty> SaveFiles(FileCollectionEventArgs e, HttpContext httpCurrent , string folder)
        {
            string mapPathAddress = httpCurrent.Request.MapPath(httpCurrent.Request.ApplicationPath) + @"\" + folder + @"\";
            
            CreateFolder(mapPathAddress);
            HttpFileCollection oHttpFileCollection = e.PostedFiles;
            bool result = false;
            HttpPostedFile oHttpPostedFile = null;
             List<FileProperty>  savedFileNames = new List<FileProperty>();
            if (e.HasFiles)
            {
                foreach (string fileName in oHttpFileCollection)
                {
                    FileProperty fp = new FileProperty();
                    oHttpPostedFile = oHttpFileCollection[fileName];
                    string saveRandomName = System.IO.Path.GetRandomFileName() + System.IO.Path.GetExtension(oHttpPostedFile.FileName);
                    fp.NewFileName = saveRandomName;
                    fp.OriginalFileName = oHttpPostedFile.FileName;
                    if (oHttpPostedFile.ContentLength >= 0)
                    {
                        savedFileNames.Add(fp);
                        oHttpPostedFile.SaveAs(mapPathAddress + saveRandomName );
                        result = true;
                    }
                }

            }
            return savedFileNames;
        }
    }
}